package SGNet

import (
	"encoding/binary"
	"fmt"
	proto "github.com/golang/protobuf/proto"
	log "misc/seelog"
	"net"
	"time"
)

type Session struct {
	IP net.IP

	ConnectTime    time.Time
	LastPacketTime time.Time
	PacketTime     time.Time
	keepAliveTime  int64
	Conn           net.Conn

	out            chan []byte
	in             chan []byte
	InMessageQueue chan Message
	UserData       interface{}
}

func (this *Session) SendPacket(Msgid int, message proto.Message) {
	data, err := proto.Marshal(message)
	if err != nil {
		log.Info(err)
	}
	if err := recover(); err != nil {
		fmt.Println(err)
		fmt.Println(Msgid)
	}
	SendData := make([]byte, len(data)+6)
	binary.BigEndian.PutUint32(SendData, uint32(len(data)))
	binary.BigEndian.PutUint16(SendData[4:], uint16(Msgid))
	copy(SendData[6:], data)
	this.out <- SendData
}

func (this *Session) SetAliveTime(aliveTime int64) {
	msg := Message{}
	msg.Id = uint16(0)
	msg.Param = map[string]interface{}{
		"AliveTime": aliveTime,
	}
	this.InMessageQueue <- msg
}

func (this *Session) Close() {
	if ClientLostMessage != nil {
		ClientLostMessage(this)
		//等待一会确保断线消息已被处理
		<-time.After(time.Millisecond * 10)
	}
	close(this.in)
	close(this.out)
}
